#!/usr/bin/env slua

-- Milis Linux 2.3 Servis Yönetim Betiği
-- milisarge 2023/09

package.path  = "/usr/milis/mps/lua/?.lua" .. ";".. package.path
package.path  = "/etc/init/?.lua"     .. ";".. package.path

local serpent = require('serpent')
local c = require ("config")

local config_file="/etc/init/config.lua"

l5=require("l5")
if os.getenv("init_color") == nil then
	l5.setenv("init_color","1")
end

function help()
	if arg[0] == "/usr/milis/bin/servis" then
	
	print ("Milis Linux 2.3 Servis Yönetim Betiği")
	print ("-------------------------------------")
	local script="servis"
	print(script,"ekle","servis_adı","| servis sistemine ekleme")
	print(script,"sil","servis_adı","| servis sisteminden silme")

	print(script,"aktif","servis_adı","| servis otomatik başlatma")
	print(script,"pasif","servis_adı","| servis otomatik başlatmama")

	print(script,"kos","servis_adı","| servis başlatma")
	print(script,"dur","servis_adı","| servis durdurma")
	print(script,"yuk","servis_adı","| servis yeniden yükleme")

	print(script,"bil","servis_adı","| servis bilgisi")

	print(script,"liste",'            ',"| aktif servis listesi")
	print(script,"eliste",'            ',"| ekli servis listesi")
	print(script,"dliste",'            ',"| depo servis listesi")
	
	else
	
	print ("Milis Linux 2.3 Service Management")
        print ("-------------------------------------")
        local script="service"
        print(script,"add","service","| add service")
        print(script,"del","service","| remove service")

        print(script,"active","service","| autostart service")
        print(script,"pasive","service","| disable autostart service")

        print(script,"start","service","| start service")
        print(script,"stop","service","| stop service")
        print(script,"reload","service","| reload service")

        print(script,"status","service","| service status")

        print(script,"list",'    ',"| autostart service list")
        print(script,"alist",'   ',"| added service list")
        print(script,"rlist",'   ',"| service repo list")

	os.exit()
	end
end

function not_ready()
	print("hazır değil!")
	os.exit()
end

function service_not_found(srv)
	if srv == nil then 
		print("servis parametresi eksik!")
	else
		print(srv.." servisi bulunamadı!")
	end
	os.exit()
end

function auth()
	if shell("id -u") ~= "0" then 
		print ("Yetkili çalıştırın!")
		os.exit()
	end
end

function shell(command)
	local handle=io.popen(command)
	local result=handle:read('*all')
	handle:close()
	-- komut çıktısı sonu yeni satır karakterin silinmesi - en sondaki \n
	if result:sub(-1) == "\n" then
		result=result:sub(1,-2)
	end
	return result
end

function content(file)
    local f = assert(io.open(file, "rb"))
    local content = f:read("*all")
    f:close()
    return content
end

function update_tasks()
	local data=serpent.block(c)
	print(serpent.block(c.tasks))
	--not_ready()
	io.output(io.open(config_file, "w"))
	io.write("local config=")
	io.write(data)
	io.write("\n")
	io.write("return config")
	io.write("\n")  
	io.close()
end

function list(srv)
	for _,s in ipairs(c.tasks) do
		print(s)
	end
end

function elist(srv)
	for s,_ in pairs(service_list("/etc/init")) do
		print(s)
	end
end

function dlist(srv)
	for s,_ in pairs(service_list("/usr/milis/ayarlar/init")) do
		print(s)
	end
end

function service_list(path)
	local services = {}
	for fn in shell("ls "..path.."/*.lua"):gmatch('[^\n]+') do
	   if content(fn):match("local task={") then
		local name = fn:match("[^/]*.lua$")
		services[name:sub(0, #name - 4)]=true
	   end
	end
	return services
end

function add(srv)
	if not srv then service_not_found(srv) end
	os.execute("cp -fv /usr/milis/ayarlar/init/"..srv..".lua /etc/init/")
end

function delete(srv)
	if not srv then service_not_found(srv) end
	local cmd="rm -v /etc/init/"..srv..".lua"
	--print(cmd)
	os.execute(cmd)
end

function run(srv)
	if service_list("/etc/init")[srv] == nil then service_not_found(srv) end
	local cmd="/etc/init/init.lua start "..srv
	--print(cmd)
	os.execute(cmd)
end

function stop(srv)
	if service_list("/etc/init")[srv] == nil then service_not_found(srv) end
	os.execute("/etc/init/init.lua stop "..srv)
end

function reload(srv)
	if service_list("/etc/init")[srv] == nil then service_not_found(srv) end
	os.execute("/etc/init/init.lua reload "..srv)
end

function activate(srv)
	if not srv then service_not_found(srv) end
	local add=true
	for _,t in ipairs(c.tasks) do
		if t == srv then
			add=false
		end
	end
	if add then table.insert(c.tasks,srv) end
	update_tasks()
end

function deactivate(srv)
	if not srv then service_not_found(srv) end
	local ntasks={}
	for _,t in ipairs(c.tasks) do
		if t ~= srv then
			table.insert(ntasks,t)
		end
	end
	c.tasks=ntasks
	update_tasks()
end

function info(srv)
    if service_list("/etc/init")[srv] == nil then service_not_found(srv) end
    local cmd="/etc/init/init.lua status "..srv
    --print(cmd)
    os.execute(cmd)
end

command=arg[1]
service=arg[2]

auth()

if command == nil then help() end

commands={
	liste=list,
	dliste=dlist,
	eliste=elist,
	ekle=add,
	sil=delete,
	kos=run,
	dur=stop,
	yuk=reload,
	aktif=activate,
	pasif=deactivate,
	bil=info,
	-- english
	list=list,rlist=dlist,alist=elist,add=add,del=delete,reload=reload,
	start=run,stop=stop,active=activate,pasive=deactivate,status=info,
}

if commands[command] then commands[command](service)
else help()
end

--notlar
--verbose çıktıları için os.execute()
-- içerik okunacak shell çıktıları için shell()
-- dosya içerik için content()
